# Copyright (c) 2008 POTI, Inc.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

require 'rubygems'
require 'active_record'

module Drupal
  class DrupalDatabase < ActiveRecord::Base
    self.abstract_class = true
    establish_connection $config['drupal_database']
    logger = Logger.new(File.open('drupal.database.log', 'a'))
    def to_s
      attributes.each {|name, value|
        puts "#{name}: #{value}"
      }
    end
  end
  
  class User < DrupalDatabase
    set_table_name 'users'
    set_primary_key 'uid'
  end

  class Node < DrupalDatabase
    set_table_name 'node'
    set_primary_key 'nid'
    self.inheritance_column = ''
    
    belongs_to :user, :class_name => 'Drupal::User', :foreign_key => 'uid'
    
    has_many :comments, :class_name => 'Drupal::Comment', :foreign_key => 'nid'
    
    has_and_belongs_to_many :terms, :association_foreign_key => 'tid',
                                    :foreign_key => 'nid',
                                    :join_table => 'term_node',
                                    :class_name => 'Drupal::Term'
    
    def to_wordpress_name
      self.title.downcase.gsub("\s", '-').gsub(/[^\w\d\-]/, '').gsub(/-+/, '-')
    end
    
  end
  
  class Term < DrupalDatabase
    set_table_name 'term_data'
    set_primary_key 'tid'
  end

  class Comment < DrupalDatabase
    set_primary_key 'cid'
    belongs_to :node, :class_name => 'Drupal::Node', :foreign_key => 'nid'
  end
  
  class UrlAlias < DrupalDatabase
    set_table_name 'url_alias'
    
    def self.find_aliases_for_node(node)
      find(:all, :conditions => ["src like 'node/#{node.nid}'"])
    end
  end
end
